package top.hidoctor.auscultation.feature.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.tang.util.AppUtil;
import com.tang.util.BigDecimalUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.bean.PatientLocalInfo;
import top.hidoctor.auscultation.utils.BlueToothDataUtils;
import top.hidoctor.auscultation.utils.MyInternalStorage;
import top.hidoctor.auscultation.view.MyEcgView;

public class HistoryDetailAct extends BaseActivity {

    private TextView tvFileName, tvAge, tvGender, tvRemark, tvName, tvTime;
    private String path;
    private ImageView ivBofang;
    private MediaPlayer mediaPlayer;
    private SeekBar seekBar;
    private int state = 0; // 0 零状态  1 开始 2 暂停
    private String wavInfo, pcmInfo;
    private Handler hanlder;
    ArrayList<Float> list = new ArrayList<>();
    private int duration;
    private MyEcgView ecgView;
    private HorizontalScrollView horizontalScroll;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_history_detail);
        initView();
        initEvent();
    }

    private void initEvent() {
        hanlder = new Handler();
        Intent intent = getIntent();
        PatientLocalInfo info = (PatientLocalInfo) intent.getSerializableExtra("info");
        try {
            pcmInfo = new MyInternalStorage(HistoryDetailAct.this).get(info.getPcmFileName());
            wavInfo = new MyInternalStorage(HistoryDetailAct.this).get(info.getFileName());

        } catch (IOException e) {
            e.printStackTrace();
        }

        if (info != null) {
            tvFileName.setText(info.getFileName());
//            tvAge.setText(info.getAge());
//            tvGender.setText(info.getGender().equals("F") ? "女" : "男");
//            tvRemark.setText(info.getRemark());
//            tvName.setText(info.getName());
            path = getFilesDir().getAbsolutePath() + "/" + info.getFileName();
        }
        //1.初始化midiaplayer
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.reset();
            //2.设置要播放的资源位置  path 可以是网络路径 也可以是本地路径
            mediaPlayer.setDataSource(path);
            //3.准备播放
            mediaPlayer.prepare();
            duration = mediaPlayer.getDuration();
            tvTime.setText(AppUtil.stringForTime(duration));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //初始化波形图数据
        hanlder.post(new Runnable() {
            @Override
            public void run() {
                getLocation(pcmInfo);
            }
        });

    }

    /**
     * 每两个字节一组
     * @param pcmInfo
     */
    private void getLocation(String pcmInfo) {
        for (int i = 0; i < pcmInfo.length() - 1; i += 4) {
            Float point = BlueToothDataUtils.getComplement(pcmInfo.substring(i, i + 4));
            list.add(point);
        }
        ecgView.setMdata(list);

    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        final TextView tvTitle = findViewById(R.id.tv_title);
        toolbar.setNavigationIcon(R.mipmap.ic_back_left);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        tvTitle.setText("详细信息");
        tvFileName = findViewById(R.id.tv_file_name);
        seekBar = findViewById(R.id.seekBar);
        tvAge = findViewById(R.id.tv_age);
        tvGender = findViewById(R.id.tv_gender);
        tvRemark = findViewById(R.id.tv_remark);
        tvName = findViewById(R.id.tv_name);
        tvTime = findViewById(R.id.tv_time);
        ivBofang = findViewById(R.id.iv_bofang);
        ecgView = findViewById(R.id.ecg_view);
        horizontalScroll = findViewById(R.id.horizontal_scroll);

        ivBofang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("TAG", "initEvent: " + list.size()); // 82600
                Log.i("TAG", "initEvent: " + 0.04 * list.size()); // 82600
                if (state == 0) { // 播放状态
                    state = 1;
                    startMusic();
                } else if (state == 1) {// 暂停状态
                    state = 2;
                    pauseMusic();

                } else if (state == 2) { //继续播放
                    state = 1;
                    restartmusic();
                }
            }
        });

        setSeekBarChange();
    }

    /**
     * 重置
     */
    private void restartmusic() {
        mediaPlayer.start();
        ivBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_bofang));
    }

    /**
     * 暂停
     */
    private void pauseMusic() {
        mediaPlayer.pause();
        ivBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_zanting));
    }


    /**
     * 播放音视频
     */
    private void startMusic() {
        mediaPlayer.start();
        ivBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_bofang));
        //5.更新进度条
        updateSeekBar();
    }


    /**
     * 监听 seekbar变化
     */
    private void setSeekBarChange() {

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            //当进度改变
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            //当开始拖动
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            //当拖动停止的时候调用
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                seekTo(seekBar.getProgress());
            }
        });
    }

    /**
     * 实现指定播放的位置
     *
     * @param position
     */
    public void seekTo(int position) {
        if (mediaPlayer != null) {
            mediaPlayer.seekTo(position);
        }
    }

    /**
     * 更新seekbar
     */
    private void updateSeekBar() {
        // ecg总长度
        final int width = (int) (0.04 * list.size());
        //1.获取当前播放的总长度
        final int duration = mediaPlayer.getDuration();
        //2.使用Timer 定时器 去定时获取当前进度
        final Timer timer = new Timer();
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                //3.一秒获取一次当前进度
                final int currentPosition = mediaPlayer.getCurrentPosition();
                // 设置seekBar进度
                seekBar.setMax(duration);
                //当前进度
                seekBar.setProgress(currentPosition);

                horizontalScroll.scrollTo((int) Math.round(BigDecimalUtil.div(currentPosition, duration) * width), 0);
                Log.e("TAG", "run: " + currentPosition);
                Log.e("TAG", "run2: " + Math.round(BigDecimalUtil.div(currentPosition, duration) * width));
                Log.e("TAG", "run2:duration " + duration);
                HistoryDetailAct.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvTime.setText(AppUtil.stringForTime(currentPosition));
                    }
                });
            }
        };
        //100毫秒后 每隔1秒 执行一次run方法
        timer.schedule(task, 0, 100);

        //当歌曲执行完毕时，把timer 和 timertask 取消
        //设置播放完成的监听
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                timer.cancel();
                task.cancel();
                state = 0;
                ivBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_zanting));
                //清楚 lineChart
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
    }
}
